<?php

defined('SYSPATH') or die('No direct access allowed.');

/**
 * Service User 
 */
class Model_Service_User extends Domain_Dao_User {

    public $_rep;

    /**
     * 
     */
    public function __construct() {
        $o_repository_manager = new Domain_Repositories_RepositoryManager;
        $this->_rep = $o_repository_manager->getUserRepository();
    }

    /**
     *
     * @return <type>
     */
    public function load($id) {
        return $this->_rep->load($id);
    }

    /**
     *
     * @param <type> $offset
     * @param <type> $limit
     * @param <type> $filter
     * @param <type> $sort
     * @param <type> $count
     * @return <type>
     */
    public function load_all($is_count = false, $offset = null, $limit = null, $filter = null, $sort = null) {
        return $this->_rep->load_all($offset, $limit, $filter, $sort, $is_count);
    }

    /**
     *
     * @param Domain_Entities_Entity $o_entity
     * @return <type> 
     */
    public function insert($o_entity) {
        return $this->_rep->insert_by($o_entity);
    }

    /**
     *
     * @param Domain_Entities_Entity $o_entity
     * @return <type>
     */
    public function update($o_entity) {
        return $this->_rep->update_by($o_entity);
    }

    /**
     *
     * @param <type> $id
     * @return <type> 
     */
    public function delete($id) {
        return $this->_rep->delete_by($id);
    }

    /**
     *
     * @param <type> $o_user
     * @return <type> 
     */
    public static function usernameadmin_available($o_user) {
        $s_category = new Model_Service_User;
        $s_category->_rep->clear();
        $s_category->_rep->builder_select('username', array('where' => '='), trim(strtolower($o_user->getUsername())));
        //$s_category->_rep->builder_select('password', array('where' => '='), Controller_Helper_Authentication::hash($o_user->getPassword()));
        $s_category->_rep->builder_select('password', array('where' => '='), $o_user->getPassword());
        $s_category->_rep->builder_select('active', array('where' => '='), 1);

        if (trim($o_user->get__Admin()) == 'admin') {
            $s_category->_rep->builder_select('outsideaccess', array('where' => '='), 1);
        }

        $n_count = $s_category->_rep->get_count();
        return $n_count <= 0 ? false : true;
    }

    /**
     *
     * @param <type> $o_user
     * @return <type> 
     */
    public static function check_expired_time($o_user) {
        $s_user = new Model_Service_User();
        $_o_user = $s_user->get_by_username($o_user->getUsername());
        if (empty($_o_user)) {
            return false;
        }
        $o_entity_user = $_o_user->get_data();
        if ($o_entity_user->getId() <= 0) {
            return false;
        }
        $o_su = $o_entity_user->get_Sessionuser();
        $o_entity_su = $o_su->get_data();
        $expired_time = $o_entity_su->getExpired();
        if ($o_entity_su->getId() <= 0) {
            return true;
        }

        if ($o_entity_su->getSession_Key() == Security::token()) {
            return true;
        }
        $todays_date = date("Y-m-d H:i:s", strtotime("now"));

        $today = strtotime($todays_date);
        $expiration_date = strtotime($expired_time);

        if ($expiration_date > $today) {
            return false;
        } else {
            return true;
        }
    }

    /**
     *
     * @param <type> $username
     * @param <type> $password
     * @param <type> $file
     * @return <type> 
     */
    public function validate_login($username, $password, $act, $file) {
        $this->_rep->clear();
        $this->_rep->values(Arr::map('trim', array('username' => $username, 'password' => $password), array('username')));
        $o_valid = $this->_rep->validation();
        $o_valid->rule('username', 'not_empty');
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            return $errors['username'];
        }
        $o_valid->rule('password', 'not_empty');
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            return $errors['password'];
        }
        $o_user = new Domain_Entities_User();
        $o_user->setUsername($username);
        $o_user->setPassword($password);
        $o_user->set__Admin($act);
        $o_valid->bind(':model', $o_user);
        $o_valid->rule('username', 'Model_Service_User::usernameadmin_available', array(':model'));
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            return $errors['username'];
        }

        //check expired time

        return "";
    }

    /**
     *
     * @param <type> $o_user
     * @return <type> 
     */
    public static function username_add_available($o_user) {
        $s_category = new Model_Service_User;
        $s_category->_rep->clear();
        $s_category->_rep->builder_select('username', array('where' => '='), trim($o_user->getUsername()));

        $n_count = $s_category->_rep->get_count();
        return $n_count > 0 ? false : true;
    }

    /**
     *
     * @param <type> $o_user
     * @param <type> $file
     * @return <type> 
     */
    public function valid_add($o_user, $file) {
        $this->_rep->clear();
        $this->_rep->values(Arr::map('trim', array('username' => $o_user->getUsername(), 'password' => $o_user->getPassword(), 'email' => $o_user->getEmail()), array('username', 'email')));
        $o_valid = $this->_rep->validation();
        $o_valid->rule('username', 'not_empty');
        $r = array();
        $r['msg'] = "";
        $r['error'] = 0;
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            $r['msg'] = $errors['username'];
            $r['id'] = 'username';
            $r['error'] = 1;
            return $r;
        }
        $o_valid->rule('password', 'not_empty');
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            $r['msg'] = $errors['password'];
            $r['id'] = 'password';
            $r['error'] = 1;
            return $r;
        }
        $o_valid->bind(':model', $o_user);
        $o_valid->rule('username', 'Model_Service_User::username_add_available', array(':model'));
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            $r['msg'] = $errors['username'];
            $r['id'] = 'username';
            $r['error'] = 1;
            return $r;
        }
        return $r;
    }

    /**
     *
     * @param <type> $o_user
     * @return <type> 
     */
    public static function username_edit_available($o_user) {
        $s_category = new Model_Service_User;
        $s_category->_rep->clear();
        $s_category->_rep->builder_select('username', array('where' => '='), trim($o_user->getUsername()));

        $s_category->_rep->builder_select('id', array('where' => '!='), trim($o_user->getId()));
        $n_count = $s_category->_rep->get_count();
        return $n_count > 0 ? false : true;
    }

    /**
     *
     * @param <type> $o_user
     * @return <type>
     */
    public static function email_edit_available($o_user) {
        $s_category = new Model_Service_User;
        $s_category->_rep->clear();
        $s_category->_rep->builder_select('email', array('where' => '='), trim($o_user->getEmail()));
        $s_category->_rep->builder_select('id', array('where' => '!='), trim($o_user->getId()));
        $n_count = $s_category->_rep->get_count();
        return $n_count > 0 ? false : true;
    }

    /**
     *
     * @param <type> $o_user
     * @param <type> $file
     * @return <type>
     */
    public function valid_edit($o_user, $file) {
        $this->_rep->clear();
        $this->_rep->values(Arr::map('trim', array('username' => $o_user->getUsername(), 'password' => $o_user->getPassword(), 'email' => $o_user->getEmail()), array('username', 'email')));
        $r = array();
        $r['msg'] = "";
        $r['error'] = 0;
        $o_valid = $this->_rep->validation();
        $o_valid->rule('username', 'not_empty');
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            $r['msg'] = $errors['username'];
            $r['id'] = 'username';
            $r['error'] = 1;
            return $r;
        }
        $o_valid->rule('password', 'not_empty');
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            $r['msg'] = $errors['password'];
            $r['id'] = 'password';
            $r['error'] = 1;
            return $r;
        }
        $o_valid->bind(':model', $o_user);
        $o_valid->rule('username', 'Model_Service_User::username_edit_available', array(':model'));
        if (!$o_valid->check()) {
            $errors = $o_valid->errors($file);
            $r['msg'] = $errors['username'];
            $r['id'] = 'username';
            $r['error'] = 1;
            return $r;
        }

        return $r;
    }

    /**
     *
     * @param <type> $s_id
     * @return <type>
     */
    public function delete_by_ids($s_id) {
        $obj = $this->_rep->db_delete($this->_rep->table_name())
                ->where('id', 'in', DB::expr('(' . $s_id . ')'));
        return $this->_rep->db_execute($obj);
    }

    /**
     *
     * @param <type> $s_username
     * @return <type> 
     */
    public function get_by_username($s_username) {
        $this->_rep->clear();
        $s_username = strtolower(trim($s_username));
        $this->_rep->select();
        $this->_rep->builder_select('username', array('where' => '='), $s_username);
        return $this->_rep->query();
    }

    /**
     *
     * @param <type> $s_username
     * @return <type> 
     */
    public function get_by_location_id($location_id, $id = null) {
        $this->_rep->clear();
        $s_username = strtolower(trim($location_id));
        $this->_rep->select();
        $this->_rep->builder_select('location_id', array('where' => '='), $location_id);
        if (!empty($id)) {
            $this->_rep->builder_select('id', array('where' => '!='), $id);
        }
        return $this->_rep->query();
    }

    /**
     *
     * @param <type> $s_username
     * @return <type> 
     */
    public function get_by_username_update($s_username, $id) {
        $this->_rep->clear();
        $s_username = strtolower(trim($s_username));
        $this->_rep->select();
        $this->_rep->builder_select('username', array('where' => '='), $s_username);
        $this->_rep->builder_select('id', array('where' => '!='), $id);
        return $this->_rep->query();
    }

    public function get_permission_for_cache($user_id) {
        $s_ug = new Model_Service_User_Group();
        $s_user = new Model_Service_User();
        $s_per = new Model_Service_Permission();
        $s_gp = new Model_Service_Group_Permission();
        $s_group = new Model_Service_Group();
        $s_up = new Model_Service_User_Permission();

        $a_result1 = array();
        $a_result2 = array();
        //get group permissin
        $s_per->_rep->clear();
        $s_per->_rep->select();
        $s_per->_rep->join($s_gp->_rep->table_name());
        $s_per->_rep->on("id", "=", $s_gp->_rep->table_name() . ".permission_id");
        $s_per->_rep->join($s_group->_rep->table_name());
        $s_per->_rep->on($s_group->_rep->table_name() . ".id", "=", $s_gp->_rep->table_name() . ".group_id");
        $s_per->_rep->join($s_ug->_rep->table_name());
        $s_per->_rep->on($s_group->_rep->table_name() . ".id", "=", $s_ug->_rep->table_name() . ".group_id");
        $s_per->_rep->join($s_user->_rep->table_name());
        $s_per->_rep->on($s_user->_rep->table_name() . ".id", "=", $s_ug->_rep->table_name() . ".user_id");
        $s_per->_rep->where($s_user->_rep->table_name() . ".id", '=', $user_id);
        $a_per = $s_per->_rep->query_all();
        if (!empty($a_per) && !empty($a_per[0])) {
            foreach ($a_per as $o_per) {
                $o_entity_per = $o_per->get_data();
                $s_pc = $o_entity_per->get_Permissioncontroller();
                $o_entity_pc = $s_pc->get_data();
                $o_entity_per->set__Controller($o_entity_pc->getName());
                $o_entity_per->clear_data_foreign_key();
                $a_result1[] = $o_entity_per;
            }
        }
        //getget permission user
        $s_per->_rep->clear();
        $s_per->_rep->select();
        $s_per->_rep->join($s_up->_rep->table_name());
        $s_per->_rep->on("id", "=", $s_up->_rep->table_name() . ".permission_id");
        $s_per->_rep->join($s_user->_rep->table_name());
        $s_per->_rep->on($s_user->_rep->table_name() . ".id", "=", $s_up->_rep->table_name() . ".user_id");
        $s_per->_rep->where($s_user->_rep->table_name() . ".id", '=', $user_id);
        $a_per = $s_per->_rep->query_all();
        if (!empty($a_per) && !empty($a_per[0])) {
            foreach ($a_per as $o_per) {
                $o_entity_per = $o_per->get_data();
                $s_pc = $o_entity_per->get_Permissioncontroller();
                $o_entity_pc = $s_pc->get_data();
                $o_entity_per->set__Controller($o_entity_pc->getName());
                $o_entity_per->clear_data_foreign_key();
                $a_result2[] = $o_entity_per;
            }
        }
        $a_result = array_merge($a_result1, $a_result2);
        return $a_result;
    }

    public function get_user_for_permission($str_per_name) {
        $s_ug = new Model_Service_User_Group();
        $s_user = new Model_Service_User();
        $s_per = new Model_Service_Permission();
        $s_gp = new Model_Service_Group_Permission();
        $s_group = new Model_Service_Group();
        $s_up = new Model_Service_User_Permission();

        $a_result1 = array();
        $a_result2 = array();
        //get group permissin
        $this->_rep->clear();
        $this->_rep->select();
        $this->_rep->join($s_ug->_rep->table_name());
        $this->_rep->on("id", "=", $s_ug->_rep->table_name() . ".user_id");
        $this->_rep->join($s_group->_rep->table_name());
        $this->_rep->on($s_group->_rep->table_name() . ".id", "=", $s_ug->_rep->table_name() . ".group_id");
        $this->_rep->join($s_gp->_rep->table_name());
        $this->_rep->on($s_group->_rep->table_name() . ".id", "=", $s_gp->_rep->table_name() . ".group_id");
        $this->_rep->join($s_per->_rep->table_name());
        $this->_rep->on($s_per->_rep->table_name() . ".id", "=", $s_gp->_rep->table_name() . ".permission_id");
        $this->_rep->builder_select($s_per->_rep->table_name() . ".name", array('where' => 'in'), $str_per_name);
        $a_user = $this->_rep->query_all();
        if (!empty($a_user) && !empty($a_user[0])) {
            foreach ($a_user as $o_user) {
                $o_entity_user = $o_user->get_data();
                $o_entity_user->clear_data_foreign_key();
                $a_result1[] = $o_entity_user;
            }
        }
        //getget permission user
        $this->_rep->clear();
        $this->_rep->select();
        $this->_rep->join($s_up->_rep->table_name());
        $this->_rep->on("id", "=", $s_up->_rep->table_name() . ".user_id");
        $this->_rep->join($s_per->_rep->table_name());
        $this->_rep->on($s_per->_rep->table_name() . ".id", "=", $s_up->_rep->table_name() . ".permission_id");
        $this->_rep->builder_select($s_per->_rep->table_name() . ".name", array('where' => 'in'), $str_per_name);
        $a_user = $this->_rep->query_all();
        if (!empty($a_user) && !empty($a_user[0])) {
            foreach ($a_user as $o_user) {
                $o_entity_user = $o_user->get_data();
                $o_entity_user->clear_data_foreign_key();
                $a_result2[] = $o_entity_user;
            }
        }
        $a_result = array_merge($a_result1, $a_result2);
        return $a_result;
    }

    /**
     *
     * @param <type> $customer_id
     * @param <type> $type
     * @param <type> $limit
     * @param <type> $offset
     * @param <type> $count
     * @return <type>
     * @author : Nguyen Tan Phuong
     */
    public function get_all_user($count = false, $filter = null, $sort, $limit = null, $offset = null) {
        $this->_rep->clear();
        $this->_rep->build_filter($filter);
        $this->_rep->build_sort($sort);
        $this->_rep->builder_select('id', array('limit' => $limit, 'offset' => $offset));
        if ($count) {
            return $this->_rep->get_count();
        }
        return $this->_rep->query_all();
    }

    public function get_gcm() {
        $this->_rep->clear();
        $this->_rep->builder_select('device', array('where' => '='), 1);
        $this->_rep->builder_select('notification', array('where' => '='), 1);
        return $this->_rep->query_all(array('google_id' => 'google_id'))->as_array(NULL, 'google_id');
    }

    public function get_apple() {
        $this->_rep->clear();
        $this->_rep->builder_select('device', array('where' => '='), 2);
        $this->_rep->builder_select('notification', array('where' => '='), 1);
        return $this->_rep->query_all(array('apple_id' => 'apple_id','language_id'=>'language_id','id'=>'id'));
    }
    
    public function update_google_id($google_id){
        $obj =  $this->_rep->db_update()->value("google_id", '')
                ->value("device", '0')
                ->where('google_id', '=', $google_id);
        $this->_rep->db_execute($obj);
    }
    
    public function update_apple_id($apple_id){
        $obj =  $this->_rep->db_update()->value("apple_id", '')
                ->value("device", '0')
                ->where('apple_id', '=', $apple_id);
        $this->_rep->db_execute($obj);
    }

}

?>
